package com.rivues.module.manage.web.service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rivues.core.RivuDataContext;
import com.rivues.module.platform.web.exception.BusinessException;
import com.rivues.module.platform.web.model.Organ;
import com.rivues.module.platform.web.model.Role;
import com.rivues.module.platform.web.model.User;
import com.rivues.module.platform.web.model.UserOrgan;
import com.rivues.module.platform.web.model.UserRole;


/**
 * 抽象class
 * @author leon
 *
 */
public abstract class AccountServiceAbs {
	/**
	 * log4j
	 */
	private final Logger logger = LoggerFactory.getLogger(AccountServiceAbs.class);
	
	/**
	 * 用户导入
	 */
	public List<String> importuser(InputStream inputStream,User loginUser) throws BusinessException {
		List<String> users = null;
		try {
			POIFSFileSystem pofs = new POIFSFileSystem(inputStream);
			HSSFWorkbook workbook = new HSSFWorkbook(pofs);
			users = processImport(workbook, loginUser.getOrgi(),loginUser.getId());
			inputStream.close();
		} catch(Exception ce){
			logger.error("导入用户出错，错误信息为:" + ce.getMessage(), ce);
		}
		return users;
	}
	/**
	 * 导入实现
	 * @param sheet
	 * @param orgi
	 * @param creater
	 * @throws Exception
	 */
	protected abstract List<String> processImport(HSSFWorkbook workbook,String orgi,String creater) throws Exception;
	
	 
	
	 /**
     * 获取单元格数据内容为字符串类型的数据
     * 
     * @param cell Excel单元格
     * @return String 单元格数据内容
     */
	protected String getStringCellValue(Cell cell) {
    	if (cell == null) return "";
    	cell.setCellType(Cell.CELL_TYPE_STRING);
    	String strCell = cell.getStringCellValue();
        return StringUtils.isNotBlank(strCell)?StringUtils.trim(strCell):strCell;
    }
	
	/**
	 * 验证组织是否合法
	 * @param organName
	 * @param parentOgranName
	 * @return
	 */
	protected boolean validate(String organName,String parentOgranName,String orgi){
		//不全，需要重新优化
		List<Organ> list = RivuDataContext.getService().findAllByCriteria(DetachedCriteria.forClass(Organ.class).add(Restrictions.eq("orgi", orgi)).add(Restrictions.eq("name", organName)));
		if (list != null && list.size() >0)return false;
		return true;
	}
	
	
	/**
	 * 获取所有组织信息
	 * @param orgi
	 * @return
	 */
	protected Map<String, Organ> getAllOrgan(String orgi){
		Map<String, Organ> map = new HashMap<String, Organ>();
		List<Organ> list = RivuDataContext.getService().findAllByCriteria(DetachedCriteria.forClass(Organ.class).add(Restrictions.eq("orgi", orgi)));
		if(list == null || list.size()<=0) return map;
		for(Organ tmp : list){
			map.put(tmp.getName(), tmp);
		}
		Organ tmp = new Organ();
		tmp.setId("0");
		map.put("0",tmp);
		return map;
	}
	
	/**
	 * 获取所有角色map
	 * @param orgi
	 * @return
	 */
	protected Map<String,Role> getAllRole(String orgi){
		Map<String, Role> map = new HashMap<String, Role>();
		List<Role> list = RivuDataContext.getService().findAllByCriteria(DetachedCriteria.forClass(Role.class).add(Restrictions.eq("orgi", orgi)));
		if(list == null || list.size()<=0) return map;
		for(Role role : list){
			map.put(role.getName(), role);
		}
		return map;
	}
	

	/**
	 * 批量导入用户
	 * @param list
	 */
	protected void batchAddUser(Map<String,User> userMap,Map<String,String> addRoleMap) throws Exception{
		List<User> userList = new ArrayList<User>();
		List<UserRole> userRoleList = new ArrayList<UserRole>();
		List<UserOrgan> userOrganList = new ArrayList<UserOrgan>();
		for(String key : userMap.keySet()){
			User user = userMap.get(key);
			//username是否重复
			List<Organ> userTmplist = RivuDataContext.getService().findAllByCriteria(DetachedCriteria.forClass(User.class).add(Restrictions.eq("username",user.getUsername())).add(Restrictions.eq("orgi", user.getOrgi())));
			if (!userTmplist.isEmpty())continue;
			userList.add(user);
			
			//插入用户组织信息
			if (user.getProperty().containsKey("organ")){
				String organ = String.valueOf(user.getProperty().get("organ"));
				String[] strs = organ.split(",");
				if (strs == null ||  strs.length<0)continue;
				for(String str : strs){
					List<Organ> tmplist = RivuDataContext.getService().findAllByCriteria(DetachedCriteria.forClass(Organ.class).add(Restrictions.eq("name",str.trim())).add(Restrictions.eq("orgi", user.getOrgi())));
					if (tmplist.isEmpty())continue;
					UserOrgan userOgran = new UserOrgan();
					userOgran.setOrgi(user.getOrgi());
					userOgran.setUserid(user.getId());
					userOgran.setOrganid(tmplist.get(0).getId());
					userOrganList.add(userOgran);
				}
			} else {
				//如果用户组织为空，则默认挂靠根组织
				UserOrgan userOgran = new UserOrgan();
				userOgran.setOrgi(user.getOrgi());
				userOgran.setUserid(user.getId());
				userOgran.setOrganid("0");
				userOrganList.add(userOgran);
			}
			
			
			//插入用户角色信息
			if(user.getProperty().containsKey("role")){
				String role = String.valueOf(user.getProperty().get("role"));
				String[] strs = role.split(",");
				if (strs == null ||  strs.length<0) continue;
				for(String str : strs){
					String id = this.getRoleId(addRoleMap, str, user.getOrgi());
					if(null == id) continue;
					UserRole userRole = new UserRole();
					userRole.setOrgi(user.getOrgi());
					userRole.setRoleid(id);
					userRole.setUserid(user.getId());
					userRoleList.add(userRole);
				}
			}
		}
		logger.info("导入用户信息过滤完成，导入用户数为:"+userList.size()+",导入用户角色关系数据为:"+userRoleList.size()+"，导入用户组织关系数据为:"+userOrganList.size());
		//批量保存用户、组织、角色信息
		if (userList.size()>0)RivuDataContext.getService().saveBat(userList);
		if (userOrganList.size()>0)RivuDataContext.getService().saveBat(userOrganList);
		if (userRoleList.size()>0)RivuDataContext.getService().saveBat(userRoleList);
	}
	
	/**
	 * 获取角色Id
	 * @param addRoleMap
	 * @param roleName
	 * @param orgi
	 * @return
	 */
	private String getRoleId(Map<String, String> addRoleMap,String roleName,String orgi){
		if (addRoleMap.containsKey(roleName)) return addRoleMap.get(roleName);
		List<Role> list = RivuDataContext.getService().findAllByCriteria(DetachedCriteria.forClass(Role.class).add(Restrictions.eq("name", roleName)).add(Restrictions.eq("orgi", orgi)));
		if(list != null && list.size() >0) {
			return list.get(0).getId();
		}
		return null;
	}
}
